package com.server.questionbank.snframe.controller.Course.Chapter;


import com.server.questionbank.snframe.controller.Course.pojo.Chapter.EditorChapters;
import com.server.questionbank.snframe.controller.Course.pojo.Chapter.UpdateLessonResource;
import com.server.questionbank.snframe.controller.Course.pojo.Exercises.UpdateKnowledge;
import com.server.questionbank.snframe.domain.Course.Chapter.LessonsResource;
import com.server.questionbank.snframe.domain.Course.Chapter.TLessons;
import com.server.questionbank.snframe.domain.Course.Chapter.UpdateChapter;
import com.server.questionbank.snframe.domain.Course.Chapter.TChapter;
import com.server.questionbank.snframe.domain.Course.Resource.CourseResource;
import com.server.questionbank.snframe.domain.Course.TCourse;
import com.server.questionbank.snframe.domain.ResDTO.ResponseResult;
import com.server.questionbank.snframe.domain.User.TUser;
import com.server.questionbank.snframe.mapper.Course.Resource.CourseFilesMapper;
import com.server.questionbank.snframe.service.CourseService.Member.CusMemberService;
import com.server.questionbank.snframe.service.CourseService.Resource.CourseFileService;
import com.server.questionbank.snframe.service.CourseService.TChapterService;
import com.server.questionbank.snframe.service.CourseService.TCourseService;
import com.server.questionbank.snframe.service.CourseService.TKnowledgeService;
import com.server.questionbank.snframe.service.UsersService.UsersService;
import com.server.questionbank.snframe.util.MinIo.MinIoBucket;
import com.server.questionbank.snframe.util.MinIo.MinIoFactory;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/course/chapter")
public class CourseChapterController {
    @Autowired
    private CourseFileService courseFileService;
    @Autowired
    private CourseFilesMapper courseFilesMapper;
    @Autowired
    private MinIoFactory minIoFactory;
    @Autowired
    private TCourseService courseService;
    @Autowired
    private TChapterService tChapterService;
    @Autowired
    private TKnowledgeService tKnowledgeService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private CusMemberService cusMemberService;

    // 获取课时视频播放
//    @GetMapping("/Lessons")
//    @ApiOperation("课时视频")
    @GetMapping("/preview/video")
    public void previewVideo(@RequestParam("resourceId") Long resourceId,
                             HttpServletRequest request,
                             HttpServletResponse response) {
        try {
            // 获取用户信息
            TUser user = usersService.getLoginUser();
            if (user == null) {
                response.setStatus(404);
                return;
            }

            // 获取课时资源信息
            LessonsResource resource = tChapterService.getLessonResourceInfo(resourceId);
            if (resource == null)
            {
                response.setStatus(404);
                return;
            }

            // 获取课时信息
            TLessons lesson = tChapterService.getLessonInfo(resource.getLessonsId());
            if (lesson == null)
            {
                response.setStatus(404);
                return;
            }

            // 获取章节信息
            TChapter chapter = tChapterService.getChapterInfo(lesson.getChapterId());
            if (chapter == null)
            {
                response.setStatus(404);
                return;
            }

            // 获取课程信息
            TCourse course = courseService.getCourseById(chapter.getCourseId());
            if (course == null)
            {
                response.setStatus(404);
                return;
            }

            // 权限验证
            if (!(cusMemberService.getMemberPermission(course.getCourseId(), user.getUserId()).getPermissionFlags() > 0
                    || course.getCreateBy() == user.getUserId()))
            {
                response.setStatus(404);
                return;
            }

            MinIoBucket minIoBucket = minIoFactory.openBucket("course");

            // 获取文件名
            String fileName = resource.getResourceUrl();

            long fileSize = minIoBucket.getFileSize(fileName);
            String contentType = minIoBucket.getFileType(fileName);
            if (contentType == null) contentType = "application/octet-stream";

            String range = request.getHeader("Range");
            long start = 0, end = fileSize - 1;

            if (range != null && range.startsWith("bytes=")) {
                String[] parts = range.replace("bytes=", "").split("-");
                if (!parts[0].isEmpty()) start = Long.parseLong(parts[0]);
                if (parts.length > 1 && !parts[1].isEmpty()) end = Long.parseLong(parts[1]);
            }

            // 合法性校验
            if (start > end || start < 0 || end >= fileSize) {
                response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                response.setHeader("Content-Range", "bytes */" + fileSize);
                return;
            }

            long contentLength = end - start + 1;

            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            response.setContentType(contentType);
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-Length", String.valueOf(contentLength));
            response.setHeader("Content-Range", String.format("bytes %d-%d/%d", start, end, fileSize));

            long startTime = System.currentTimeMillis(); // 下载开始时间
            // 建议：MinIO Range 下载代替 skip
            try (InputStream inputStream = minIoBucket.downloadFile(fileName, start, end);
                 OutputStream out = response.getOutputStream()) {

                byte[] buffer = new byte[8192];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
            } catch (IOException clientAbortException) { }
            finally {
                long endTime = System.currentTimeMillis(); // 下载结束时间
                long duration = endTime - startTime; // 真实观看耗时（毫秒）

                long watchedBytes = contentLength;
                double watchedSecondsEstimate = duration / 1000.0; // 粗略估计
                System.out.println("视频播放成功，观看时长：" + watchedSecondsEstimate + "秒");
            }
        } catch (Exception e)
        {
            System.err.println("视频播放失败：" + e.getMessage());
        }
    }

    // 更新章节
    @PostMapping("/update")
    public ResponseResult<Boolean> update(@RequestBody EditorChapters editorChapters) {
        TUser user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("未登录，请先登录");
        TCourse course = courseService.getCourseById(editorChapters.getCourseId());
        if (course == null) return ResponseResult.error("课程不存在");
        if (course.getCreateBy() != user.getUserId()) return ResponseResult.error("无权限修改课程");
        return ResponseResult.success(tChapterService.updateChapters(editorChapters.getCourseId(), editorChapters.getChapters(), user.getUserId()));
    }

    // 创建知识点
    @PostMapping("/createKnowledge")
    public ResponseResult<Boolean> createKnowledge(@RequestBody UpdateKnowledge createKnowledge) {
        TUser user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("未登录，请先登录");
        TChapter chapter = tChapterService.getChapterInfo(createKnowledge.getCameraId());
        if (chapter == null) return ResponseResult.error("章节不存在");
        TCourse course = courseService.getCourseById(chapter.getCourseId());
        if (course == null) return ResponseResult.error("课程不存在");
        if (course.getCreateBy() != user.getUserId()) return ResponseResult.error("无权限修改课程");
        createKnowledge.setCourseId(course.getCourseId());
        return ResponseResult.success(tKnowledgeService.createKnowledge(createKnowledge.toTKnowledge()));
    }

    // 移除知识点
    @PostMapping("/removeKnowledge")
    public ResponseResult<Boolean> removeKnowledge(@RequestBody UpdateKnowledge removeKnowledge) {
        TUser user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("未登录，请先登录");
        TChapter chapter = tChapterService.getChapterInfo(removeKnowledge.getCameraId());
        if (chapter == null) return ResponseResult.error("章节不存在");
        TCourse course = courseService.getCourseById(chapter.getCourseId());
        if (course == null) return ResponseResult.error("课程不存在");
        if (course.getCreateBy() != user.getUserId()) return ResponseResult.error("无权限修改课程");
        removeKnowledge.setCourseId(course.getCourseId());
        return ResponseResult.success(tKnowledgeService.removeKnowledge(removeKnowledge.getRecordId()));
    }

    // 更新课时资源
    @PostMapping("/updateLessonResource")
    public ResponseResult<Boolean> updateLessonResource(@RequestBody UpdateLessonResource updateLessonResource) {
        TUser user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("未登录，请先登录");
        TLessons lesson = tChapterService.getLessonInfo(updateLessonResource.getLessonsId());
        if (lesson == null) return ResponseResult.error("课时不存在");
        TChapter chapter = tChapterService.getChapterInfo(lesson.getChapterId());
        if (chapter == null) return ResponseResult.error("章节不存在");
        TCourse course = courseService.getCourseById(chapter.getCourseId());
        if (course == null) return ResponseResult.error("课程不存在");
        if (course.getCreateBy() != user.getUserId()) return ResponseResult.error("无权限修改课程");
        return ResponseResult.success(tChapterService.updateLessonResource(
                lesson.getLessonsId(), updateLessonResource.getLessonsResourceList(), user.getUserId()
        ));
    }

    // 上传课时资源文件
    @PostMapping("/uploadLessonsResourceFile")
    public ResponseResult<Boolean> upload(@RequestParam("file") MultipartFile file, @RequestParam("resource") Long resourceId) throws Exception {
        if (file == null) return ResponseResult.error("上传文件不能为空");
        if (resourceId == null) return ResponseResult.error("课时资源ID不能为空");
        TUser user = usersService.getLoginUser();
        if (user == null)  return ResponseResult.error("未登录，请先登录");
        LessonsResource lessonsResource = tChapterService.getLessonResourceInfo(resourceId);
        if (lessonsResource == null) throw new IllegalArgumentException("❌ 课时资源不存在");
        TLessons lessons = tChapterService.getLessonInfo(lessonsResource.getLessonsId());
        if (lessons == null) throw new IllegalArgumentException("❌ 课时不存在");
        TChapter chapter = tChapterService.getChapterInfo(lessons.getChapterId());
        if (chapter == null) throw new IllegalArgumentException("❌ 章节不存在");
        TCourse course = courseService.getCourseById(chapter.getCourseId());
        if (course == null) throw new IllegalArgumentException("❌ 课程不存在");
        if (course.getCreateBy() != user.getUserId()) throw new IllegalArgumentException("❌ 无权限上传课时资源");

        // 上传文件
        try {
            tChapterService.uploadFlie(file, course.getCourseId(), chapter.getChapterId(), lessons.getLessonsId(), lessonsResource);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseResult.success(true);
    }

    // 获取课时资源
    @PostMapping("/getLessonResource")
    public ResponseResult<List<LessonsResource>> getLessonResource(@RequestBody Map<String, Long> map) {
        if (map.get("lessonsId") == null) return ResponseResult.error("缺少课时ID");
        TUser user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("未登录，请先登录");
        TLessons lesson = tChapterService.getLessonInfo(map.get("lessonsId"));
        if (lesson == null) return ResponseResult.error("课时不存在");
        TChapter chapter = tChapterService.getChapterInfo(lesson.getChapterId());
        if (chapter == null) return ResponseResult.error("章节不存在");
        TCourse course = courseService.getCourseById(chapter.getCourseId());
        if (course == null) return ResponseResult.error("课程不存在");

        if (course.getCreateBy() != user.getUserId() && cusMemberService.getMemberPermission(course.getCourseId(), user.getUserId()).getPermissionFlags() < 1)
            return ResponseResult.error("无权获取课时信息");
        return ResponseResult.success(tChapterService.getLessonResource(lesson.getLessonsId()));
    }
}
